package com.ludomancy.insane;

import java.awt.Graphics;
import java.awt.Point;

import com.ludomancy.gamelib.ImageStrip;
import com.ludomancy.gamelib.Randomizer;
import com.ludomancy.gamelib.ResourceManager;

public class Creature extends InsaneEntity
{
	private Point target;
	private static final int SPEED = 2;
	private boolean dead = false;
	private ImageStrip sprite;
	
	public Creature(Point pos)
	{
		super(pos);
		sprite = new ImageStrip(ResourceManager.getImage("creature.png"), 8, 8);
	}
	
	public void update()
	{
		if(dead)
		{
			return;
		}
		
		if(target == null)
		{
			target = new Point(Randomizer.getRandom(100,parent.width), Randomizer.getRandom(100,parent.height));
		}
		
		// am I in deep shit?
		reactToEnvironment();
		
		Point next = getNextPos(target, SPEED);
		boolean isPassable = isPassable(next); 
		if(isPassable)
		{
			pos = next;
		}
		
		if(!isPassable || next.equals(target))
		{
			target = null;
		}
		
	}
	
	private void reactToEnvironment()
	{
		Point tPos = toTile();
		int terrain = Game.game.earth.terrain[tPos.x][tPos.y];
		if(terrain == Earth.TERRAIN_WATER)
		{
			// argh!
			dead = true;
		}
	}

	private boolean isPassable(Point next)
	{
		Point tPos = toTile();
		Point tNext = toTile(next);
		// Am I in a pit?
		if(Game.game.earth.depth[tPos.x][tPos.y] > 0)
		{
			// no climbing
			if(Game.game.earth.depth[tNext.x][tNext.y] == 0)
			{
				return false;
			}
		}
		
		// no swimming
		if(Game.game.earth.terrain[tNext.x][tNext.y] == Earth.TERRAIN_WATER)
		{
			return false;
		}
		
		return true;
	}
	
	public void paint(Graphics g, int x, int y)
	{
		int frame = dead? 1 : 0;
		sprite.paint(g, frame, x, y);
	}

}
